#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->ReadConfig();

    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);    // 禁止最大化按钮
    setFixedSize(this->width(),this->height());                     // 禁止拖动窗口大小

    //状态栏初始化
    msgLabel = new QLabel();
    this->ui->statusBar->addPermanentWidget(msgLabel);

    QString strBuffer;
    QDateTime time;
    time = QDateTime::currentDateTime();
    strBuffer = time.toString("yyyy-MM-dd hh:mm:ss");

    ui->lineEdit_time_in2->setText(strBuffer);
    this->on_time_button2_clicked();

    this->ReadSqlConfig();
}

MainWindow::~MainWindow()
{
    delete ui;
}

bool MainWindow::ReadConfig()
{
    if (access("config.ini", F_OK) < 0)
    {
            return false;
    }

    QSettings settings("config.ini", QSettings::IniFormat);

    settings.beginGroup("explorer");
    const QStringList &key_list = settings.childKeys();
    int i = 0;
    for(auto iter : key_list)
    {
        m_explorer_map[i] = settings.value(iter, 0).toString().toStdString();
        i++;
    }
    settings.endGroup();

    ui->comboBox->addItems(key_list);

    return true;
}

bool MainWindow::ReadSqlConfig()
{
    if (access("./sql/config.ini", F_OK) < 0)
    {
        QMessageBox::critical(0, QObject::tr("无法打开数据库"),
        "sql/config.ini不存在", QMessageBox::Cancel);
        return false;
    }

    QSettings settings("./sql/config.ini", QSettings::IniFormat);

    settings.beginGroup("project");
    m_project_name = settings.value("name").toString().toStdString();
    settings.endGroup();
    if(m_project_name.empty())
    {
        QMessageBox::critical(0, QObject::tr("无法打开项目"),
        "项目名称为空", QMessageBox::Cancel);
        return false;
    }

    settings.beginGroup("sql");
    m_sql_name = settings.value("sqlname").toString().toStdString();
    m_sql_password = settings.value("sqlpassword").toString().toStdString();
    settings.endGroup();
    if(m_sql_name.empty() || m_sql_password.empty())
    {
        QMessageBox::critical(0, QObject::tr("无法打开数据库"),
        "sql账号密码为空", QMessageBox::Cancel);
        return false;
    }

    for(int i = 0; i < 10; i++)
    {
        std::string str = "cross_";
        str += std::to_string(i + 1);
        settings.beginGroup(str.c_str());
        int port = settings.value("cross_port").toInt();
        settings.endGroup();
        if(port <= 0)
        {
            break;
        }
    }

    return true;
}

void MainWindow::on_pushButton_clicked()
{
    std::string str = "explorer ";
    int index = ui->comboBox->currentIndex();
    auto iter = m_explorer_map.find(index);
    if(iter != m_explorer_map.end())
    {
        str += iter->second;
    }

    str += " &";

    QString qstr = str.c_str();
    this->msgLabel->setText(qstr);

    ::system(str.c_str());
}

void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    QString qstr = to_string(index).c_str();
    //if(this->msgLabel != nullptr)
        //this->msgLabel->setText(qstr);
}

void MainWindow::on_time_button_clicked()
{
    try
    {
        QString qstr = ui->lineEdit_time_in->text();
        std::string str_timestamp = qstr.toStdString();

        time_t ll_time = std::stoll(str_timestamp);
        struct tm *lt = localtime(&ll_time);
        char nowtime[24] = { 0 };
        strftime(nowtime, 24, "%Y-%m-%d %H:%M:%S", lt);
        ui->lineEdit_time_out->setText(nowtime);
    }
    catch(...)
    {
        QMessageBox::information(NULL, "ERROR", "edit \"timestamp\"");
    }
}

void MainWindow::on_time_button2_clicked()
{
    try
    {
        QString qstr = ui->lineEdit_time_in2->text();
        std::string str_timestamp = qstr.toStdString();
        const char *str_time = str_timestamp.c_str();

        struct tm stm;
        int iY, iM, iD, iH, iMin, iS;

        memset(&stm,0,sizeof(stm));

        iY = atoi(str_time);
        iM = atoi(str_time+5);
        iD = atoi(str_time+8);
        iH = atoi(str_time+11);
        iMin = atoi(str_time+14);
        iS = atoi(str_time+17);

        stm.tm_year=iY-1900;
        stm.tm_mon=iM-1;
        stm.tm_mday=iD;
        stm.tm_hour=iH;
        stm.tm_min=iMin;
        stm.tm_sec=iS;

        long long out_timestamp = mktime(&stm);
        ui->lineEdit_time_out2->setText(std::to_string(out_timestamp).c_str());
    }
    catch(...)
    {
        QMessageBox::information(NULL, "ERROR", "edit \"yyyy-MM-dd hh:mm:ss\"");
    }
}

int excute_sql_file(QSqlDatabase &db, const char * sql_file_path)
{
    int iRet = 0;
    QFile qfile(sql_file_path);
    if (!qfile.exists())
    {
        QMessageBox::critical(0, QObject::tr("无法打开文件"),
        "文件不存在！", QMessageBox::Cancel);

        return -1;
    }

    if (!qfile.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return -1;
    }
    QTextStream in(&qfile);
    in.setCodec("UTF-8");
    QString qstr_file_data = in.readAll();
    QSqlQuery qsql(db);
    QStringList qstrlist_sql =  qstr_file_data.split(";");
    for (int i = 0; i < qstrlist_sql.size() - 1; i++) {
        QString qstr_sql_part = qstrlist_sql.at(i).toUtf8();
        bool sql_result = qsql.exec(qstr_sql_part);
        if (!sql_result) {
            QSqlError sql_error = qsql.lastError();
            std::cout << sql_error.text().toStdString() << std::endl;
            std::cout << sql_error.number() << std::endl;
            iRet = -1;
            break;
        }
    }

    return iRet;
}

void MainWindow::on_create_db_button_clicked()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setUserName(m_sql_name.c_str());
    db.setPassword(m_sql_password.c_str());
    if (!db.open())
    {
        QSqlError sql_error = db.lastError();
        ofstream os("debug.txt");
        os << sql_error.text().toStdString() << std::endl;
        os << "sql_error number=";
        os << sql_error.number() << std::endl;

        QMessageBox::critical(0, QObject::tr("无法打开数据库"),
        "无法创建数据库连接！ ", QMessageBox::Cancel);
        return;
    }

    std::string str_exec = "CREATE DATABASE if not exists uc01_cn_cross_3 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
    QSqlQuery query = db.exec(str_exec.c_str());
    /*
    db.setDatabaseName("realname");
    if (db.open())
    {
        excute_sql_file(db, "test.sql");
    }
    */

    std::string str_system = "qtcreate.bat";
    str_system += " ";
    str_system += m_sql_name;
    str_system += " ";
    str_system += m_sql_password;
    str_system += " ";
    str_system += "uc01_cn_cross_3";
    system(str_system.c_str());
}
